import CreateApp, { appMap } from "./app";

class MyElement extends HTMLElement {
  name: string = "";
  url: string = "";

  // 创建元素实例时触发
  constructor() {
    super();
  }

  // 自定义组件的属性
  static get observedAttributes() {
    return ["name", "url"];
  }

  // 元素插入DOM时触发
  connectedCallback() {
    console.log("micro app 连接成功=================");
    const app = new CreateApp({
      name: this.name,
      url: this.url,
      container: this,
    });
    appMap.set(app.name, app);
  }

  // 元素从DOM移除时触发
  disconnectedCallback() {
    console.log("micro app 断开了连接=================");
    const app = appMap.get(this.name);
    app?.unmount();
  }
}

export function defineElement() {
  if (!window.customElements.get("micro-app")) {
    window.customElements.define("micro-app", MyElement);
  }
}
